import { observable, action, toJS } from 'mobx';
import API from '../../apis';
import { message } from 'antd';
import _ from "lodash";

class BatchStore {
    @observable html = [] as any[];
    @observable rows = 0;
    @observable cols = 0;
    @observable levelspacing = 0;
    @observable verticalspacing = 0;
    @observable loading = true;
    interface: Function;
    @observable params: any;
    @observable CodeLeft = '';
    @observable CodeRight ='';
    @observable postion = '';
    @observable windowTitle = '';
    @action
    update = (param: any) => {
        for (let key in param) {
            this[key] = param[key]
        }
    }

    @action
    updateParams = (params: any) => {
        let temp = !_.isEqual(toJS(this.params), params);
        this.params = params;
        if (temp) {
            this.getCode(params);
        }
    }
    @action
    getCode = ({ guid, ...params }) => {
        this.interface = { barCode: API.getBarCode, qrCode: API.getQrCode }[guid];
        this.interface(params).then(action(({ status, error, html, rows, cols, levelspacing, verticalspacing,postion,CodeLeft,CodeRight,windowTitle }) => {
            if (status == '1') {
                this.html = html;
                this.rows = rows;
                this.cols = cols;
                this.levelspacing = levelspacing;
                this.verticalspacing = verticalspacing;
                this.CodeLeft = CodeLeft;
                this.CodeRight = CodeRight;
                this.postion = postion;
                this.windowTitle = windowTitle;
                this.loading = false;
                this.autoPrint();
            } else {
                message.error(error);
                throw error;
            }
        }))
    }

    @action
    autoPrint = () => {
        if (this.params && this.params.from && this.params.from == "card") {
            setTimeout(() => {
                window.print();
            }, 300);
        }
    }

    @action
    clearState = () => {
        this.html = [] ;
        this.rows = 0;
        this.cols = 0;
        this.levelspacing = 0;
        this.verticalspacing = 0;
        this.loading = false;
        this.params ={};
    }
}
export default BatchStore;